package com.hjm.project.agentInfo.agentInfo.service.impl;

import java.io.File;
import java.util.*;
import java.util.regex.Pattern;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hjm.common.exception.BusinessException;
import com.hjm.common.utils.DateUtils;
import com.hjm.common.utils.LogUtils;
import com.hjm.common.utils.StringUtils;
import com.hjm.common.utils.fastdfs.FastDFSClient;
import com.hjm.common.utils.http.HttpUtils;
import com.hjm.common.utils.request.AutoLoadData;
import com.hjm.common.utils.security.ShiroUtils;
import com.hjm.framework.config.CustomConfig;
import com.hjm.framework.shiro.service.PasswordService;
import com.hjm.framework.web.domain.AjaxResult;
import com.hjm.project.ActActive.ActActive.domain.ActActive;
import com.hjm.project.ActActive.ActActive.mapper.ActActiveMapper;
import com.hjm.project.accounts.accounts.domain.Accounts;
import com.hjm.project.accounts.accounts.mapper.AccountsMapper;
import com.hjm.project.agentDateCen.agentDateCen.domain.AgentDateCen;
import com.hjm.project.agentDateCen.agentDateCen.mapper.AgentDateCenMapper;
import com.hjm.project.agentInfo.agentActActive.domain.AgentActActive;
import com.hjm.project.agentInfo.agentActActive.mapper.AgentActActiveMapper;
import com.hjm.project.agentInfo.agentInfo.domain.AgentInfoExport;
import com.hjm.project.agentInfo.agentInfo.domain.AgentInfoNextVo;
import com.hjm.project.agentInfo.agentInfo.utils.Utils;
import com.hjm.project.agentInfo.point.domain.TaxPoint;
import com.hjm.project.agentInfo.point.mapper.TaxPointMapper;
import com.hjm.project.agentInfo.record.domain.ClientRecord;
import com.hjm.project.agentInfo.record.mapper.ClientRecordMapper;
import com.hjm.project.agentInfo.total.domain.AgentTotal;
import com.hjm.project.agentInfo.total.mapper.AgentTotalMapper;
import com.hjm.project.area.mapper.AreaMapper;
import com.hjm.project.cardBag.domain.CardBag;
import com.hjm.project.cardBag.mapper.CardBagMapper;
import com.hjm.project.clientImg.clientImg.domain.ClientImg;
import com.hjm.project.clientImg.clientImg.mapper.ClientImgMapper;
import com.hjm.project.gearsRecord.gearsRecord.domain.GearsRecord;
import com.hjm.project.gearsRecord.gearsRecord.mapper.GearsRecordMapper;
import com.hjm.project.gears_info.domain.GearsInfo;
import com.hjm.project.gears_info.mapper.GearsInfoMapper;
import com.hjm.project.merchantInfo.merRecord.domain.MerRecord;
import com.hjm.project.merchantInfo.merRecord.mapper.MerRecordMapper;
import com.hjm.project.merchantInfo.merchantInfo.mapper.MerchantInfoMapper;
import com.hjm.project.riskControl.riskmerblack.domain.Riskmerblack;
import com.hjm.project.riskControl.riskmerblack.mapper.RiskmerblackMapper;
import com.hjm.project.salesman.salesman.domain.Salesman;
import com.hjm.project.salesman.salesman.mapper.SalesmanMapper;
import com.hjm.project.system.user.domain.User;
import com.hjm.project.system.user.domain.UserRole;
import com.hjm.project.system.user.mapper.UserMapper;
import com.hjm.project.system.user.mapper.UserRoleMapper;
import com.hjm.project.terminal.agentTargetInfo.agentTargetInfo.domain.AgentTargetInfo;
import com.hjm.project.terminal.agentTargetInfo.agentTargetInfo.mapper.AgentTargetInfoMapper;
import com.yxhd.encrypt.EncryptUtils;
import lombok.SneakyThrows;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import com.hjm.project.agentInfo.agentInfo.mapper.AgentInfoMapper;
import com.hjm.project.agentInfo.agentInfo.domain.AgentInfo;
import com.hjm.project.agentInfo.agentInfo.service.IAgentInfoService;
import com.hjm.common.utils.text.Convert;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 服务商申请Service业务层处理
 *
 * @author LOVE
 * @date 2020-11-18
 */
@Service
public class AgentInfoServiceImpl implements IAgentInfoService {
    @Resource
    private AgentInfoMapper agentInfoMapper;        //代理商信息
    @Resource
    private AreaMapper areaMapper;                  //区域
    @Resource
    private UserMapper userMapper;                  //用户
    @Resource
    private AccountsMapper accountsMapper;          //结算账户
    @Resource
    private UserRoleMapper userRoleMapper;          //用户角色分配
    @Resource
    private GearsInfoMapper gearsInfoMapper;        //档位
    @Resource
    private MerchantInfoMapper merchantInfoMapper;  //商户
    @Resource
    private ClientRecordMapper clientRecordMapper;  //操作记录相关
    @Resource
    private GearsRecordMapper gearsRecordMapper;    //修改档位记录
    @Resource
    private ClientImgMapper clientImgMapper;        //图片相关
    @Resource
    private PasswordService passwordService;        //密码服务(加密修改密码)
    @Resource
    private AgentTotalMapper totalMapper;           //统计代理
    @Resource
    private AgentDateCenMapper agentDateCenMapper;  //代理初始化数据
    @Resource
    private TaxPointMapper taxPointMapper;          //税点
    @Resource
    private SalesmanMapper salesmanMapper;          //业务员
    @Resource
    private AgentTargetInfoMapper agentTargetInfoMapper;    //档位分配记录
    @Resource
    private CardBagMapper cardBagMapper;            //卡包数据表
    @Resource
    private AgentTotalMapper agentTotalMapper;
    @Resource
    private MerRecordMapper merRecordMapper;
    @Resource
    private RiskmerblackMapper riskmerblackMapper;
    @Resource
    private AgentActActiveMapper agentActActiveMapper;
    @Resource
    private ActActiveMapper actActiveMapper;


    /**
     * 导出查询服务商列表
     *
     * @param agentInfo 服务商列表
     * @return 服务商集合
     */
    @Override
    public List<AgentInfoExport> selectAgentInfoExportList(AgentInfo agentInfo) {
        List<AgentInfoExport> agentInfoList = agentInfoMapper.selectAgentInfoExportList(agentInfo);
        for (AgentInfoExport info : agentInfoList) {
            //联系人手机号脱敏
            info.setPhonenumber(Utils.dealPhone(info.getPhonenumber()));
        }
        return agentInfoList;
    }

    /**
     * 获取本级和所有下级代理信息
     *
     * @param agentNum
     * @return
     */
    @Override
    public List<AgentInfoNextVo> selectAgentInfoNext(String agentNum) {
        List<AgentInfoNextVo> agentInfoList = agentInfoMapper.selectAgentInfoNext(agentNum);
        return agentInfoList;
    }


    @Override
    public AgentInfo selectAgentInfoByAgent1(AgentInfo agentInfo) {
        return agentInfoMapper.selectAgentInfoByAgent1(agentInfo);
    }

    @Override
    public List<AgentInfo> selectAgentInfoByAgent2(AgentInfo agentInfo) {
        List<AgentInfo> agentInfoList = agentInfoMapper.selectAgentInfoByAgent2(agentInfo);
        return agentInfoList;
    }

    @Override
    public AgentInfo selectAgentInfoByAgentNum1(String agentNum) {
        return agentInfoMapper.selectAgentInfoByAgentNum1(agentNum);
    }

    @Override
    public AgentInfo selectAgentInfoByAgentNum2(String agentNum) {
        return agentInfoMapper.selectAgentInfoByAgentNum2(agentNum);
    }

    @Override
    public List<AgentInfo> selectAgentInfoByAgentNum3(String agentNum) {
        return agentInfoMapper.selectAgentInfoByAgentNum3(agentNum);
    }


    /**
     * 查询服务商申请
     *
     * @param agentNum 服务商申请ID
     * @return 服务商申请
     */
    @Override
    public AgentInfo selectAgentInfoById(String agentNum) {
        return agentInfoMapper.selectAgentInfoById(agentNum);
    }

    /**
     * 查询服务商申请列表
     *
     * @param agentInfo 服务商申请
     * @return 服务商申请集合
     */
    @Override
    public List<AgentInfo> selectNextAgentInfoList(AgentInfo agentInfo) {
        return agentInfoMapper.selectNextAgentInfoList(agentInfo);
    }

    /**
     * 查询服务商申请列表
     *
     * @param agentInfo 服务商申请
     * @return 服务商申请
     */
    @Override
    public List<AgentInfo> selectAgentInfoList(AgentInfo agentInfo) {
        List<AgentInfo> agentInfoList = agentInfoMapper.selectAgentInfoList(agentInfo);
        for (AgentInfo info : agentInfoList) {
            //联系人手机号脱敏
            info.setLinkPhone(Utils.dealPhone(info.getLinkPhone()));
            info.setLoginName(Utils.dealPhone(info.getLoginName()));
            if (StringUtils.isNotBlank(info.getAgentName())) {
                info.setAgentName(info.getAgentName().replaceAll("合作伙伴",""));
            }
        }
        return agentInfoList;
    }
    public List<AgentInfo> selectAgentInfoListAll(AgentInfo agentInfo) {
        List<AgentInfo> agentInfoList = agentInfoMapper.selectAgentInfoListAll(agentInfo);
        for (AgentInfo info : agentInfoList) {
            //联系人手机号脱敏
            info.setLinkPhone(Utils.dealPhone(info.getLinkPhone()));
            info.setLoginName(Utils.dealPhone(info.getLoginName()));
        }
        return agentInfoList;
    }

    /**
     * 获取所有服务商带服务商机具总量
     *
     * @Param [agentInfo]
     * @Return java.util.List<com.hjm.project.agentInfo.agentInfo.domain.AgentInfo>
     */
    public List<AgentInfo> selectAgentInfoTeamList(AgentInfo agentInfo) {
        return agentInfoMapper.selectAgentInfoTeamList(agentInfo);
    }


    /**
     * 新增服务商申请
     *
     * @param agentInfo 服务商申请
     * @return 结果
     */
    @Override
    public int insertAgentInfo(AgentInfo agentInfo) {
        return agentInfoMapper.insertAgentInfo(agentInfo);
    }


    /**
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @Description 添加服务商
     * @Param [agentinfo]
     **/
    @Transactional
    @Override
    public int saveOrUpdate(AgentInfo agent, Accounts accounts, Map param) throws Exception {
        int result = 0;
        try {
            //运营经理
            Salesman salesman = salesmanMapper.selectSalesmanById(Long.parseLong(param.get("sm_num1").toString()));
            if (salesman.getSmStatus().intValue() == 1) {
                throw new BusinessException("当前运营经理已禁用,请重新选择");
            }
            //销售经理
            Salesman salesman1 = salesmanMapper.selectSalesmanById(Long.parseLong(param.get("sm_num2").toString()));
            if (salesman1.getSmStatus().intValue() == 1) {
                throw new BusinessException("当前销售经理已禁用,请重新选择");
            }

            //服务商信息
            agent.setBelongAgent(Long.valueOf("100000000"));
            agent.setSaleAgentNum(salesman.getSaleAgentNum());
            agent.setAddName(ShiroUtils.getSysUser().getObjNo() + "-" + ShiroUtils.getSysUser().getLoginName());
            agent.setSignSale(param.get("sm_num1").toString());
            agent.setMaintain(param.get("sm_num2").toString());
            agent.setAgentNature(Long.parseLong("0"));
            //法人的姓名和身份证号码
            //TODO 服务商管理 >> 服务商信息 >>二要素认证 法人的姓名和身份证号码（要素）
            Map map = new HashMap();
            map.put("ScreenName", agent.getCommissary());
            map.put("Idnumber", agent.getIdentityNum());
           /* Map map1 = EssentialFactors.twoElements(map);
            if ("1".equals(map1.get("status").toString())) {
                throw new BusinessException("法人二要素验证失败");
            }*/
            String idCard = agent.getIdentityNum();
            agent.setLocaldate(Utils.formateDate(0));
            agent.setLocaltime(Utils.formateDate(3));
            agent.setProfitStatus(Long.valueOf("0"));
            agent.setProfitType(Long.valueOf("1"));
            agent.setAgentStatus("1");
            agent.setShowIdentitynum(agent.getIdentityNum().substring(0, 10) + "****" + agent.getIdentityNum().substring(14));
            agent.setIdentityNum(EncryptUtils.getEncrypt(agent.getIdentityNum()));
            agent.setStatus("1");
            int count = userMapper.checkLoginNameUnique(agent.getLinkPhone());
            if (count > 0) {
                throw new BusinessException("当前手机号已注册,请更换手机号");
            }

            Riskmerblack riskmerblack = new Riskmerblack();
            riskmerblack.setType("2");
            riskmerblack.setTypeVal(idCard);
            List<Riskmerblack> riskmerblacks = riskmerblackMapper.selectRiskmerblackList(riskmerblack);
            if (CollectionUtils.isEmpty(riskmerblacks)) {
                //验证通过后查看当前注册人是否注册过
                AgentInfo agentInfo = new AgentInfo();
                agentInfo.setIdentityNum(agent.getIdentityNum());
                agentInfo.setSaleType("0");
                List<AgentInfo> agentInfos = agentInfoMapper.selectAgentInfoList(agentInfo);
                if (CollectionUtils.isNotEmpty(agentInfos) && !agentInfos.get(0).getAgentStatus().equals("5")) {
                    throw new BusinessException("法人信息已注册,请更换法人信息");
                }
            }

            //生成一个服务商编号
            Integer agentNum = agentInfoMapper.getAgentNum();
            agent.setAgentNum(agentNum.toString());
            agent.setBeautiful(agentNum.toString());
            agent.setAgentName(agent.getAgentName().trim());
            agent.setBeautifulName(agent.getAgentName().trim());
            agent.setGrade("V1");
            agent.setSupportLevel("V1");
            agent.setSupportDate(DateUtils.getDate());
            //添加服务商
            int i = agentInfoMapper.insertAgentInfo(agent);
            //账户信息
            accounts.setBankAddress(param.get("province1") + "," + param.get("city1") + "," + param.get("area1"));
            accounts.setSeqId(agentNum.toString());
            accounts.setCreatedate(new Date());
            accounts.setCreateman(ShiroUtils.getSysUser().getLoginName());
            accounts.setCreateBy(ShiroUtils.getSysUser().getLoginName());
            accounts.setDaMarker(1);
            //结算卡加*
            String screenNum = Utils.hiddenCard(accounts.getScreenNum());
            accounts.setShowScreennum(screenNum);
            //结算卡加密
            accounts.setScreenNum(EncryptUtils.getEncrypt(accounts.getScreenNum()));
            //手机号加*
            String phone = accounts.getResphone();
            accounts.setShowResphone(phone.substring(0, 3) + "****" + phone.substring(8, 11));
            //手机号加密
            accounts.setResphone(EncryptUtils.getEncrypt(accounts.getResphone()));
            accounts.setAreaName(String.valueOf(param.get("areaName1")));
            //查看当前账户是对公还是对私类型
            //对公没有结算人身份照号
            int nature = accounts.getNature();
            if (nature == 2) {//对私
                String screenIdnum = accounts.getScreenIdnum();
                accounts.setScreenIdnum(EncryptUtils.getEncrypt(screenIdnum));
                accounts.setShowScreenidnum(screenIdnum.substring(0, 10) + "****" + screenIdnum.substring(14));
            } else if (nature == 1) {//对公
                accounts.setScreenIdnum("");
                accounts.setShowScreenidnum("");
            }
            //添加服务商账户
            int i2 = accountsMapper.insertAccounts(accounts);
            if (i >= 1 && i2 >= 1) {
                result = 1;
            }
            //结算卡数据同步卡包表一份
            CardBag cardBag = new CardBag();
            cardBag.setMerno(accounts.getSeqId());
            cardBag.setLocaldate(DateUtils.getDate());
            cardBag.setAdddate(DateUtils.getOnlyTime());
            cardBag.setScreenName(agent.getCommissary());
            cardBag.setScreenNum(accounts.getShowScreennum());
            cardBag.setScreenNumDense(accounts.getScreenNum());
            cardBag.setiCard(1);
            cardBag.setIdnumber(accounts.getShowScreenidnum());
            cardBag.setIsdefault(0);
            cardBag.setBankName(accounts.getBankName());
            cardBag.setBankHeadname(accounts.getBankHeadname());
            cardBag.setResphone(accounts.getShowResphone());
            cardBag.setResphoneDense(accounts.getResphone());
            cardBag.setBankNum(accounts.getBankNum());
            cardBag.setBottomPic("grey");
            cardBag.setPicno("000");
            cardBag.setBankAddress(accounts.getBankAddress());
            cardBag.setAreaName(accounts.getAreaName());
            cardBag.setCardType(1);
            int i3 = cardBagMapper.insertCardBag(cardBag);
            if (i3 <= 0) {
                throw new BusinessException("添加卡包数据失败");
            }
            //添加一个用户
            User user = new User();
            user.randomSalt();
            user.setLoginName(agent.getLinkPhone());
            user.setPassword(passwordService.encryptPassword(agent.getLinkPhone(), "00000000", user.getSalt()));
            user.setStatus("0");
            user.setDelFlag("0");
            user.setBelong(Long.parseLong("1"));
            user.setObjNo(String.valueOf(agentNum));
            user.setCreateTime(DateUtils.getNowDate());
            user.setSex("1");
            user.setCreateBy(ShiroUtils.getSysUser().getLoginName());
            user.setUserName(agent.getLinkPhone());
            user.setUserType("00");
            user.setDeptId(Long.parseLong("100"));
            int i1 = userMapper.insertUser(user);
            if (i1 <= 0) {
                throw new BusinessException("添加登录账户失败");
            }
            //默认添加为普通用户 需提升管理员联系运维人员
            UserRole userRole = new UserRole();
            userRole.setRoleId(Long.parseLong("21"));
            userRole.setUserId(user.getUserId());
            userRoleMapper.deleteUserRoleInfo(userRole);
            userRoleMapper.insertUserRole(userRole);

            //添加一条统计记录
            AgentTotal agentTotal = new AgentTotal();
            agentTotal.setAgentNum(agentNum.toString());
            agentTotal.setBelongAgent(ShiroUtils.getSysUser().getObjNo());
            totalMapper.insertAgentTotal(agentTotal);

            TaxPoint t = new TaxPoint();
            t.setAgentNum(agentNum.toString());
            t.setAddMan(ShiroUtils.getSysUser().getLoginName());

            t.setTaxPoint("0.08");
            t.setType(Long.valueOf("0"));
            taxPointMapper.insertTaxPoint(t);
            t.setTaxPoint("0.08");
            t.setType(Long.valueOf("4"));
            taxPointMapper.insertTaxPoint(t);

            TaxPoint tp = new TaxPoint();
            tp.setAgentNum(agentNum.toString());
            tp.setAddMan(ShiroUtils.getSysUser().getLoginName());

            tp.setTaxPoint("0.08");
            tp.setType(Long.valueOf("2"));
            taxPointMapper.insertTaxPoint(tp);
            tp.setTaxPoint("0.08");
            tp.setType(Long.valueOf("3"));
            taxPointMapper.insertTaxPoint(tp);

            //添加服务商的统计记录初始化数据(日 周  月)
            for (i = 1; i <= 3; i++) {
                AgentDateCen dateCen = new AgentDateCen();
                dateCen.setType(Long.parseLong(i + ""));
                //类型 1日统计 2月统计 3周统计
                //日统计 2020-11-23 月统计 2020-11，日月统计有值，周统计无值
                if (i == 1) {
                    dateCen.setBelongDate(DateUtils.getDate());
                } else if (i == 2) {
                    dateCen.setBelongDate(DateUtils.getDateYYYY_MM());
                } else if (i == 3) {
                    Map<String, String> weekDate = DateUtils.getWeekDate();
                    dateCen.setStartBelongDate(weekDate.get("startDate"));
                    dateCen.setEndBelongDate(weekDate.get("endDate"));
                }
                dateCen.setAgentNum(Long.parseLong(agentNum.toString()));
                agentDateCenMapper.insertAgentDateCen(dateCen);
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return result;
    }

    /**
     * 修改服务商申请
     *
     * @param agentInfo 服务商申请
     * @return 结果
     */
    @Override
    @Transactional
    public int updateAgentInfo(AgentInfo agentInfo) throws Exception {
        LogUtils.logInfo("开始进行调档:" + agentInfo.getAgentNum());
        //申请服务商
        AgentInfo agent = agentInfoMapper.selectAgentInfoById(agentInfo.getAgentNum());
        //目标服务商
        AgentInfo target = agentInfoMapper.selectAgentInfoById(agentInfo.getApplyAgentNum());

        //服务商状态必须是正常的  状态为0
        if (!target.getAgentStatus().equals("0")) {
            LogUtils.logInfo("当前服务商非正常状态");
            throw new BusinessException("当前服务商非正常状态");
        }

        //现在的档位信息
        GearsInfo gearsInfo1 = gearsInfoMapper.selectGearsInfoById(String.valueOf(target.getGrade()));
        //要更新后的档位信息
        GearsInfo gearsInfo = gearsInfoMapper.selectGearsInfoById(agentInfo.getSupportLevel());
        //验证分润政策(档位)是否存在
        if (gearsInfo1 == null) {
            LogUtils.logInfo("当前服务商档位不存在,请查看档位政策是否配置");
            throw new BusinessException("当前服务商档位不存在,请查看档位政策是否配置");
        }

        //不能给自己提升档位
        if (agent.getAgentNum().equals(target.getAgentNum())) {
            LogUtils.logInfo("不能给自己提升档位");
            throw new BusinessException("不能给自己提升档位");
        }

        //提升的档位不能大于自身的档位
        if (Integer.parseInt(agentInfo.getSupportLevel().split("V")[1]) > Integer.parseInt(agent.getSupportLevel().split("V")[1])) {
            LogUtils.logInfo("不能选择大于自身的档位");
            throw new BusinessException("不能选择大于自身的档位");
        }
        //选择的扶持到期日
        String date = agentInfo.getSupportDate();
       /* if (agentInfo.getSupportDate().equals("1")) {           //1个月
            date = DateUtils.getDateMonth(DateUtils.YYYY_MM_DD, 1);
        } else if(agentInfo.getSupportDate().equals("3")) {     //3个月
            date = DateUtils.getDateMonth(DateUtils.YYYY_MM_DD, 3);
        } else if(agentInfo.getSupportDate().equals("6")) {     //6个月
            date = DateUtils.getDateMonth(DateUtils.YYYY_MM_DD, 6);
        } else if(agentInfo.getSupportDate().equals("9")) {     //9个月
            date = DateUtils.getDateMonth(DateUtils.YYYY_MM_DD, 9);
        } else if(agentInfo.getSupportDate().equals("12")) {    //1年
            date = DateUtils.getYear(DateUtils.YYYY_MM_DD, 1);
        }*/

        //活动到期日
        String gradeActDate = agent.getGradeActDate();
        //当前日期和活动日期相差的天数
        Integer endDays = DateUtils.daysBetween(DateUtils.getDate(), gradeActDate);
        if (endDays < 0) {
            throw new BusinessException("扶持挡位活动已过期,不可设置挡位");
        }
        //当前选择的日期和活动到期日相差天数
        Integer selectDateEnd = DateUtils.daysBetween(date, gradeActDate);
        if (selectDateEnd < 0) {
            throw new BusinessException("选择的扶持日期天数大于扶持活动剩余天数");
        }

        //申请服务商扶持到期日所剩余天数
        String supportDate = agent.getSupportDate();
        Integer applyEndDate = DateUtils.daysBetween(date, supportDate);
        if (applyEndDate < 0) {
            throw new BusinessException("申请代理剩余扶持天数小于选择的扶持天数");
        }

        //从申请代理编号（申请代理为V9） 到 目标代理 代理之间的代理都升档不包括申请代理
        AgentInfo agentInfos = new AgentInfo();
        //申请代理
        agentInfos.setBelongAgent(Long.parseLong(agent.getAgentNum()));
        //目标代理
        agentInfos.setAgentNum(target.getAgentNum());
        List<AgentInfo> agentList = agentInfoMapper.selectBetweenAgentTop(agentInfos);
        //不存在上下级关系
        if (CollectionUtils.isEmpty(agentList)) {
            LogUtils.logInfo("申请人和目标代理商不存在上下级关系:" + agentInfo.getAgentNum());
            throw new BusinessException("申请人和目标代理商不存在上下级关系");
        }
        int count = 0;
        for (AgentInfo info : agentList) {
            LogUtils.logInfo("当前调档代理:" + info.getAgentNum() +
                    "  原档位:" + info.getGrade() +
                    " 扶持档位:" + agentInfo.getSupportLevel() +
                    " 扶持时间(月):" + agentInfo.getSupportDate());
            //获取当前服务商的等级
            Integer grade = Integer.parseInt(info.getSupportLevel().split("V")[1]);
            //要提升的服务商等级
            Integer supportLevel = Integer.parseInt(agentInfo.getSupportLevel().split("V")[1]);
            //只有代理等级小于 要提升的档位才可升档
            if (grade < supportLevel) {
                /*//查看满足提升挡位的上级级代理扶持日期是否快过期
                AgentInfo topAgent = agentInfoMapper.selectAgentInfoById(String.valueOf(info.getBelongAgent()));
                //满足提升挡位的代理的上级扶持日期必须大于等于他的下级
                if (DateUtils.compareDate(DateUtils.YYYY_MM_DD,topAgent.getSupportDate(),date)){
                    throw new BusinessException("服务商[" + info.getAgentNum() + "]扶持日期不可大于上级服务商[" + topAgent.getAgentNum() + "]");
                }*/
                //更新代理商的扶持档位
                AgentInfo agentInfo1 = new AgentInfo();
                agentInfo1.setSupportDate(date);
                agentInfo1.setSupportLevel(agentInfo.getSupportLevel());
                agentInfo1.setAgentNum(info.getAgentNum());
                //agentInfo1.setTeamGrade(agentInfo.getSupportLevel());
                int i = agentInfoMapper.updateAgentInfo(agentInfo1);
                if (i <= 0) {
                    LogUtils.logInfo("更新代理档位失败,请重试");
                    throw new BusinessException("更新代理档位失败,请重试");
                }

                //更新档位信息
                AgentTargetInfo targetInfo = new AgentTargetInfo();
                targetInfo.setInAgentNum(info.getAgentNum());     //目标
                targetInfo.setInAgentName(info.getAgentName());
                targetInfo.setOutAgentNum(agent.getAgentNum());     //申请人
                targetInfo.setOutAgentName(agent.getAgentName());
                targetInfo.setGrade("V" + supportLevel);
                targetInfo.setSource(1);
                targetInfo.setType("5");
                targetInfo.setRemark("服务商提升档位");
                targetInfo.setEndDate(date);
                agentTargetInfoMapper.insertAgentTargetInfo(targetInfo);

                //修改成功并且验证成功后增加修改档位记录（个人）
                GearsRecord gearsRecord = new GearsRecord();
                gearsRecord.setAddMan(ShiroUtils.getSysUser().getLoginName());
                gearsRecord.setBefor(info.getGrade());
                gearsRecord.setBeforDs(gearsInfo1.getDs());
                gearsRecord.setAfter(agentInfo.getSupportLevel());
                gearsRecord.setAfterDs(gearsInfo.getDs());
                gearsRecord.setAgentName(info.getAgentName());
                gearsRecord.setAgentNum(info.getAgentNum());
                gearsRecord.setUpdateDate(DateUtils.getTime());
                gearsRecord.setType("3");
                gearsRecordMapper.insertGearsRecord(gearsRecord);
                count++;
            }
        }
        LogUtils.logInfo("调档结束,调整" + count + "个服务商档位为" + agentInfo.getSupportLevel());
        return count;
    }

    /**
     * 降级服务商指定档位
     *
     * @param agentInfo 服务商申请
     * @return 结果
     */
    public int saveDemotion(AgentInfo agentInfo) throws Exception {
        //申请服务商
        AgentInfo agent = agentInfoMapper.selectAgentInfoById(agentInfo.getAgentNum());

        //现在的档位信息
        GearsInfo oldGearInfo = gearsInfoMapper.selectGearsInfoById(agentInfo.getSupportLevel());
        //要更新后的档位信息
        GearsInfo newGearInfo = gearsInfoMapper.selectGearsInfoById(agentInfo.getSupportLevel());
        if (newGearInfo == null) {
            //验证分润政策(档位)是否存在
            LogUtils.logInfo("所选档位不存在");
            throw new BusinessException("所选档位不存在");
        }
        //验证分润政策(档位)是否存在
        if (oldGearInfo == null) {
            LogUtils.logInfo("当前服务商所配置档位不存在,请查看档位政策是否配置");
            throw new BusinessException("当前服务商所配置档位不存在,请查看档位政策是否配置");
        }

        //提升的档位不能大于自身的档位
        if (Integer.parseInt(agentInfo.getSupportLevel().split("V")[1]) > Integer.parseInt(agent.getSupportLevel().split("V")[1])) {
            LogUtils.logInfo("不能选择大于自身的档位");
            throw new BusinessException("不能选择大于自身的档位");
        }
        //更新代理商的扶持档位
        AgentInfo agentInfo1 = new AgentInfo();
        agentInfo1.setSupportLevel(agentInfo.getSupportLevel());
        agentInfo1.setAgentNum(agent.getAgentNum());
        int i = agentInfoMapper.updateAgentInfo(agentInfo1);
        if (i <= 0) {
            LogUtils.logInfo("降级代理档位失败,请重试");
            throw new BusinessException("降级代理档位失败,请重试");
        }
        return i;
    }

    @Override
    @Transactional
    public int rainGrade(AgentInfo agentInfo) throws Exception {
        LogUtils.logInfo("开始进行降档:" + agentInfo.getAgentNum());

        //先获取当前要降档的代理商及它所有的下级,获取它下级档位(最高的一个)
        agentInfo.setBelongAgent(Long.parseLong(agentInfo.getAgentNum()));
        agentInfo.setAgentNum(null);
        List<AgentInfo> agentInfos = agentInfoMapper.selectBetweenAgent(agentInfo);
        List<Integer> gradeList = new ArrayList<>();
        Integer agentGrade = 1;
        for (AgentInfo info : agentInfos) {
            //当前代理的等级
            int grade = Integer.parseInt(info.getSupportLevel() == null ? info.getGrade().split("V")[1] : info.getSupportLevel().split("V")[1]);
            if (info.getAgentNum().equals(agentInfo.getBelongAgent().toString())) {
                agentGrade = grade;
                continue;
            }
            gradeList.add(grade);
        }

        //没有下级当前档位维持不变
        if (gradeList.size() == 0) {
            return agentGrade;
        }
        Integer max = Collections.max(gradeList);
        LogUtils.logInfo("降档结束,可降档位V" + max);
        return max;

    }

    /**
     * 删除服务商申请对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteAgentInfoByIds(String ids) {
        return agentInfoMapper.deleteAgentInfoByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除服务商申请信息
     *
     * @param agentNum 服务商申请ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteAgentInfoById(Long agentNum) {
        int result = -1;
        try {
            //删除服务商信息
            agentInfoMapper.deleteAgentInfoById(String.valueOf(agentNum));
            //删除服务商登录信息
            userMapper.deleteUserAgentNum(agentNum);
            //删除账户信息
            accountsMapper.deleteAccountsInfo(agentNum);
            //根据服务商编号获取用户的信息
            User user = new User();
            user.setObjNo(String.valueOf(agentNum));
            User user1 = userMapper.selectUser(user);
            if (user1 != null) {
                UserRole userRole = new UserRole();
                userRole.setUserId(user1.getUserId());
                //删除用户和角色的关联信息
                userRoleMapper.deleteUserRoleInfo(userRole);
            }
            //删除图片信息
            ClientImg clientImg = new ClientImg();
            clientImg.setClientno(agentNum.toString());
            clientImg.setObjType(Long.parseLong("1"));
            List<ClientImg> clientImgs = clientImgMapper.selectclientImgList(clientImg);
            if (CollectionUtils.isNotEmpty(clientImgs)) {
                for (ClientImg img : clientImgs) {
                    FastDFSClient.deleteFile(img.getFileid());
                }
            }
            clientImgMapper.deleteByClientImg(clientImg);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("删除失败");
        }
        return 1;
    }


    @Override
    @Transactional
    public int agentUpdate(String agent_num, String agent_status, String username, String commissary) throws Exception {
        int result = 0;
        try {
            ClientImg clientImg = new ClientImg();
            clientImg.setClientno(agent_num);
            clientImg.setObjType(Long.parseLong("1"));
            List<ClientImg> clientImgs = clientImgMapper.selectclientImgList(clientImg);
            /*if (clientImgs.size() < 5) {
                throw  new BusinessException("服务商图片资料缺少，请上传...");
            }*/
            AgentInfo agentInfo = new AgentInfo();
            agentInfo.setNote(agent_num + "-服务商资料上送审核");
            agentInfo.setAgentStatus("0");
            agentInfo.setAgentNum(agent_num);
            int ua = agentInfoMapper.updateAgentInfo(agentInfo);
            ClientRecord record = new ClientRecord();
            record.setNote(commissary);
            record.setClientno(agent_num);
            record.setObjType(Long.parseLong("1"));
            int ur = clientRecordMapper.insertClientRecord(record);
            if (ua > 0 && ur > 0) {
                result = 1;
            } else {
                throw new BusinessException("审核失败");
            }

        } catch (Exception e) {
            throw e;
        }
        return result;
    }

    @Override
    public AgentInfo getAgentOne(String agent_num) throws Exception {
        HashMap param = new HashMap();
        param.put("agent_num", agent_num);
        AgentInfo agentInfo = agentInfoMapper.selectAgentInfoById(agent_num);
        if (agentInfo != null) {
            if (!Utils.IsNull(agentInfo.getProvince())) {
                agentInfo.setSheng(agentInfo.getProvince());
            }
            if (!Utils.IsNull(agentInfo.getIdentityNum())) {
                if (agentInfo.getIdentityNum().length() > 22) {
                    agentInfo.setIdentityNum(EncryptUtils.getDecrypt(agentInfo.getIdentityNum()));
                }
            }
        }
        return agentInfo;
    }

    @Override
    public List<AgentInfo> getAgentList(String agent_num) throws Exception {
        AgentInfo agentInfo = new AgentInfo();
        agentInfo.setAgentNum(agent_num);
        List<AgentInfo> agent = agentInfoMapper.selectAgentInfoList(agentInfo);
        for (AgentInfo agentinfo : agent) {
            if (agentinfo != null) {
                if (!Utils.IsNull(agentinfo.getProvince())) {
                    agentinfo.setSheng(agentinfo.getProvince());
                }
                if (!Utils.IsNull(agentinfo.getIdentityNum())) {
                    if (agentinfo.getIdentityNum().toString().length() > 22) {
                        agentinfo.setIdentityNum(EncryptUtils.getDecrypt(agentinfo.getIdentityNum()));
                    }
                }
            }
        }
        return agent;
    }


    @Override
    public int agentRepulse(String agent_num, String note, String username, String agent_status) throws Exception {
        int result = 0;
        try {

            //服务商打回，修改服务商表状态
            AgentInfo agent = new AgentInfo();
            agent.setNote(note);
            agent.setAgentStatus("1");
            agent.setAgentNum(agent_num);
            agentInfoMapper.updateAgentInfo(agent);
            //添加操作记录
            ClientRecord clientRecord = new ClientRecord();
            clientRecord.setObjType(Long.parseLong("1"));
            clientRecord.setNote(note);
            clientRecord.setOperatorName(username);
            clientRecord.setClientno(agent_num);
            clientRecord.setNoteDetail("申请服务商-被打回");
            result = clientRecordMapper.insertClientRecord(clientRecord);
        } catch (Exception e) {
            throw e;
        }
        return result;
    }

    @Override
    public AgentInfo selectAgentInfoByAgentNum(String agentNum) {
        return agentInfoMapper.selectAgentInfoById(agentNum);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult saveStatus(AgentInfo agentInfo, String operatorName) {
        ClientRecord clientRecord = new ClientRecord();
        clientRecord.setClientno(agentInfo.getAgentNum());
        clientRecord.setNote(agentInfo.getNote());
        clientRecord.setOperatorName(operatorName);
        clientRecord.setObjType(Long.parseLong("1"));
        User user = new User();
        user.setStatus("1");
        if ("0".equals(agentInfo.getAgentStatus())) {
            user.setStatus("0");
        }
        user.setObjNo(agentInfo.getAgentNum());
        int result = agentInfoMapper.updateAgentInfo(agentInfo);
        userMapper.updateUserByObjNo(user);
        clientRecordMapper.insertClientRecord(clientRecord);
        if (result > 0) {
            return AjaxResult.success();
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error();
        }

    }

    @Override
    public AjaxResult saveCancel(AgentInfo agentInfo) {

        agentInfo.setAgentStatus("5");
        int nextNum = agentInfoMapper.getAgentNext(agentInfo.getAgentNum());
        if (nextNum > 1) {
            return AjaxResult.error("存在下级，不能注销该服务商");
        }
        //查询服务商是否绑定终端号
        int posNum = agentInfoMapper.findAgentPosNo(agentInfo.getAgentNum());
        if (posNum > 0) {
            return AjaxResult.error("已绑定机具，不能注销该服务商");
        }
        //更新服务商状态为注销  5
        int result = agentInfoMapper.updateAgentInfo(agentInfo);
        User user = new User();
        user.setStatus("1");
        user.setDelFlag("2");
        user.setObjNo(agentInfo.getAgentNum());
        userMapper.updateUserByObjNo(user);
        if (result > 0) {
            return AjaxResult.success();
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error();
        }
    }

    @Override
    public User getUserByObjNo(String agentNum) {
        return userMapper.selectUserByObjNo(agentNum);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult setLeader(List<MultipartFile> bannerFile, String agentNum, String specialGradeId, String createMan) throws Exception {
        boolean flag = false;
        for (MultipartFile v : bannerFile) {
            if (!"".equals(v.getOriginalFilename())) {
                flag = true;
            }
        }
        if (StringUtils.isNotEmpty(specialGradeId)) {
            //return AjaxResult.error("请选择奖励档位");
            if (flag == false) {
                return AjaxResult.error("请上传凭证图片");
            }
        }

        if (StringUtils.isEmpty(agentNum)) {
            return AjaxResult.error("请选择服务商");
        }

        List<ClientImg> imgList = new ArrayList<>();
        for (MultipartFile multipartFile : bannerFile) {
            //将文件转化为 file类型
            String hou = multipartFile.getOriginalFilename();
            hou = hou.substring(hou.indexOf("."), hou.length());
            //上传文件 到 fastdfs
            String fileName = agentNum + "-" + multipartFile.getName() + hou;
            File dfile = File.createTempFile("prefix", "_" + multipartFile.getOriginalFilename());
            multipartFile.transferTo(dfile);
            Map<String, String> metaList = new HashMap<String, String>();
            metaList.put("fileName", fileName);
            metaList.put("fileType", multipartFile.getName());
            metaList.put("author", createMan);
            //年月日 时分秒
            String fid = FastDFSClient.uploadFile(dfile, dfile.getName(), metaList);
            //图片查看路径
            ClientImg clientImg = new ClientImg();
            clientImg.setFastdfsGroup("group1/M00/00/00/");

            if (Utils.IsNull(fid)) {
                clientImg.setFileid("");
            } else {
                clientImg.setFileid(fid);
            }
            clientImg.setClientno(agentNum);
            clientImg.setType(45L);
            clientImg.setCreatename(createMan);
            clientImg.setObjType(1L);
            imgList.add(clientImg);
        }
        ClientImg clientImg = new ClientImg();
        clientImg.setClientno(agentNum);
        clientImg.setType(45L);
        clientImg.setObjType(1L);
        List<ClientImg> clientImgs = clientImgMapper.selectclientImgList(clientImg);
        if (clientImgs.size() > 0) {
            //删除图片服务器图片
            for (ClientImg clientImg1 : clientImgs) {
                String fid = clientImg1.getFileid();
                if (!"".equals(fid) && null != fid && !"-1".equals(fid)) {
                    FastDFSClient.deleteFile(fid);
                }
            }
            clientImgMapper.deleteByClientImg(clientImg);
        }
        if (imgList.size() > 0) {
            int result = clientImgMapper.saveBatchImage(imgList);
            if (result > 0) {
                System.out.println("图片上传成功");
            }
            imgList.clear();
        }
        AgentInfo agentInfo = new AgentInfo();
        agentInfo.setAgentNum(String.valueOf(agentNum));
        if (StringUtils.isNotBlank(specialGradeId)) {
            agentInfo.setSpecialGradeId(Long.valueOf(specialGradeId));
        } else {
            agentInfo.setSpecialGradeId(Long.valueOf("0"));
        }
        agentInfo.setAgentNature(2L);
        agentInfoMapper.updateAgentInfo(agentInfo);
        return AjaxResult.success();
    }


    @Transactional
    @Override
    public AjaxResult trialAgent(AgentInfo agentInfo, String type) {
        AgentInfo agentInfos = new AgentInfo();
        agentInfos.setAgentNum(agentInfo.getAgentNum());
        AgentInfo agentInfo1 = agentInfoMapper.selectAgentInfoList(agentInfos).get(0);
        if (agentInfo1.getAgentStatus().equals("5")) {
            throw new BusinessException("当前服务商已注销,请先确认服务商状态");
        }
        //查看是否是重复申请盟主
        if (agentInfo1.getGrade().equals("V9") && "1".equals(type) && 1 == agentInfo1.getAgentNature().intValue()) {
            throw new BusinessException("当前服务商已是正式盟主,请勿重复审核");
        }
        //重复打回
        if (agentInfo1.getGrade().equals("V9") && "0".equals(type) && 1 == agentInfo1.getAgentNature().intValue()) {
            throw new BusinessException("当前服务商已是正式盟主,请勿重复打回");
        }
        // 1 代表当前请求是审核正式服务商是否成为盟主
        if ("1".equals(type)) {
            //如果通过修改档位为 V9
            agentInfo.setGrade("V9");
            agentInfo.setSupportLevel("V9");
            agentInfo.setSupportDate(DateUtils.getYear(DateUtils.YYYY_MM_DD, 1));
            //修改团队档位
            agentInfo.setTeamGrade("V9");
            // 1 正式盟主
            agentInfo.setAgentNature(Long.parseLong("1"));
            GearsInfo gearsInfo = new GearsInfo();
            gearsInfo.setGrade(agentInfo1.getGrade());
            GearsInfo gearsInfo1 = gearsInfoMapper.selectGearsInfoList(gearsInfo).get(0);
            if (gearsInfo1 == null) {
                throw new BusinessException("基础档位数据错误,请先确认档位再申请盟主");
            }
            gearsInfo.setGrade(agentInfo.getGrade());
            GearsInfo gearsInfo2 = gearsInfoMapper.selectGearsInfoList(gearsInfo).get(0);
            if (gearsInfo2 == null) {
                throw new BusinessException("基础档位数据错误,请先确认档位再申请盟主");
            }
            ///修改成功并且验证成功后增加修改档位记录
            GearsRecord gearsRecord = new GearsRecord();
            gearsRecord.setAddMan(ShiroUtils.getSysUser().getLoginName());
            gearsRecord.setBefor(gearsInfo1.getGrade());
            gearsRecord.setBeforDs(gearsInfo1.getDs());
            gearsRecord.setAfter(gearsInfo2.getGrade());
            gearsRecord.setAfterDs(gearsInfo2.getDs());
            gearsRecord.setAgentName(agentInfo.getAgentName());
            gearsRecord.setAgentNum(agentInfo.getAgentNum());
            gearsRecord.setUpdateDate(DateUtils.getTime());
            gearsRecord.setType("1");
            gearsRecordMapper.insertGearsRecord(gearsRecord);
            //修改成功并且验证成功后增加修改档位记录（团队）
            GearsRecord tream = new GearsRecord();
            tream.setAddMan(ShiroUtils.getSysUser().getLoginName());
            tream.setAgentName(agentInfo.getAgentName());
            tream.setAgentNum(agentInfo.getAgentNum());
            tream.setUpdateDate(DateUtils.getTime());
            tream.setType("2");
            tream.setAfterPaySum("0");
            tream.setBeforPaySum("0");
            tream.setBefor(gearsInfo1.getGrade());
            tream.setAfter(gearsInfo2.getGrade());
            gearsRecordMapper.insertGearsRecord(tream);

        } else {
            agentInfo.setAgentNature(Long.parseLong("0"));
        }

        int result = agentInfoMapper.updateAgentInfo(agentInfo);

        if (result > 0) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error();
        }

    }


    /**
     * 获取本级级以下
     *
     * @Param [agentInfo, type]
     * @Return com.hjm.framework.web.domain.AjaxResult
     */
    public List<AgentInfo> selectBetweenAgent(AgentInfo agentInfo) {
        return agentInfoMapper.selectBetweenAgent(agentInfo);
    }

    /**
     * 获取本级以下所有服务商 不包含本级
     *
     * @Param [agentInfo, type]
     * @Return com.hjm.framework.web.domain.AjaxResult
     */
    public List<AgentInfo> selectBetweenAgentNoBelongAgent(AgentInfo agentInfo) {
        return agentInfoMapper.selectBetweenAgentNoBelongAgent(agentInfo);
    }


    /**
     * @return int
     * @Description 上传服务商图片资料
     * @Param [agent_num, request, createName]
     **/
    @Override
    @Transactional
    public int saveImg(String agent_num, HttpServletRequest request, String createName) throws Exception {
        AgentInfo agentInfo = new AgentInfo();
        agentInfo.setAgentNum(agent_num);
        AgentInfo agentInfo1 = agentInfoMapper.selectAgentInfoById(agent_num);
        //只有申请状态才可上传图片资料
        if (!"1".equals(agentInfo1.getAgentStatus())) {
            throw new BusinessException("当前服务商不是申请状态");
        }
        //存储图片
        List<ClientImg> imgList = new ArrayList<>();
        int result = -1;
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Iterator iter = multiRequest.getFileNames();
            boolean b = iter.hasNext();
            if (!b) {
                throw new BusinessException("图片资料不能为空");
            } else if (multiRequest.getFileMap().size() < 7) {
                throw new BusinessException("请补全图片资料");
            }
            while (b) {
                Object next = null;
                try {
                    next = iter.next();
                } catch (Exception e) {
                    break;
                }
                MultipartFile img = multiRequest.getFile(next.toString());
                if (img != null && img.getSize() != 0) {
                    //获取文件名称
                    String hou = img.getOriginalFilename();
                    //验证图片类型
                    String reg = ".+(.png|.jpg|.bmp|.jpeg)$";
                    //图片后缀类型
                    String replace = hou.toLowerCase().replaceAll(" ", "");
                    if (!Pattern.compile(reg).matcher(replace).find()) {
                        throw new BusinessException("请上传指定格式图片资料");
                    }
                    ;


                    hou = hou.substring(hou.indexOf("."), hou.length());
                    //图片查看路径
                    ClientImg clientImg = new ClientImg();
                    //上传文件 到 fastdfs
                    String fileName = agent_num + "-" + img.getName() + hou;

                    File dfile = File.createTempFile("prefix", "_" + img.getOriginalFilename());
                    img.transferTo(dfile);
                    Map<String, String> metaList = new HashMap<String, String>();
                    metaList.put("fileName", fileName);
                    metaList.put("fileType", img.getName());
                    metaList.put("author", createName);
                    metaList.put("date", Utils.formateDate(2));//年月日 时分秒
                    String fid = FastDFSClient.uploadFile(dfile, dfile.getName(), metaList);
                    clientImg.setFastdfsGroup("group1/M00/00/00/");
                    if (Utils.IsNull(fid)) {
                        clientImg.setFileid("");
                    } else {
                        clientImg.setFileid(fid);
                    }
                    clientImg.setClientno(agent_num);
                    clientImg.setType(Long.parseLong(img.getName()));
                    clientImg.setCreatename(createName);
                    clientImg.setObjType(Long.parseLong("1"));
                    imgList.add(clientImg);
                }
            }
        }
        //先获取服务商所有的图片服务器的地址 查看是否有图片
        ClientImg clientImg = new ClientImg();
        clientImg.setClientno(agent_num);
        List<ClientImg> clientImgs = clientImgMapper.selectclientImgList(clientImg);
        //存在全部删除
        //要删除的类型
        String[] types = new String[]{"1", "2", "5", "16", "7", "6", "17", "14", "15"};
        if (CollectionUtils.isNotEmpty(clientImgs)) {
            for (ClientImg img : clientImgs) {
                if (Arrays.asList(types).contains(img.getType().toString())) {
                    result = FastDFSClient.deleteFile(img.getFileid());
                    if (result == -1) {
                        throw new BusinessException("上传图片资料失败");
                    }
                    //清除旧图片成功后删除数据库的图片地址信息
                    result = clientImgMapper.deleteclientImgById(img.getId());
                    if (result <= 0) {
                        throw new BusinessException("上传图片资料失败");
                    }
                }
            }
        }
        for (ClientImg img : imgList) {
            result = clientImgMapper.insertclientImg(img);
            if (result <= 0) {
                throw new BusinessException("上传图片资料失败,请重新上传");
            }
        }

        //修改服务商状态
        //当服务商上传图片成功后 那么 自动变更为 送审状态
        AgentInfo agent = new AgentInfo();
        agent.setAgentStatus("3");
        agent.setAgentNum(agent_num);
        result = agentInfoMapper.updateAgentInfo(agent);
        if (result <= 0) {
            throw new BusinessException("上传图片失败,请重新上传");
        }
        return result;
    }


    @Override
    public List<ClientImg> getImg(ClientImg clientImg) {
        //获取所有图片地址增加 图片地址的绝对路径
        List<ClientImg> clientImgs = clientImgMapper.selectclientImgList(clientImg);
        for (ClientImg img : clientImgs) {
            img.setFileid(CustomConfig.getImgUrl() + img.getFileid());
        }
        return clientImgs;
    }


    @Override
    public AgentInfo selectBeautiful(AgentInfo agentInfo) {
        return agentInfoMapper.selectBeautiful(agentInfo);
    }


    @Override
    @Transactional
    public int updateAgent(AgentInfo agentInfo) {
        return agentInfoMapper.updateAgent(agentInfo);
    }
    public int updateAgent1(AgentInfo agentInfo) {
        return agentInfoMapper.updateAgent1(agentInfo);
    }

    @Override
    @Transactional
    public int updateAgentAll(AgentInfo agentInfo) {
        if (StringUtils.isEmpty(agentInfo.getAgentName())) {
            throw new BusinessException("服务商名称不可为空");
        }
        AgentInfo info = new AgentInfo();
        info.setAgentNameNoLike(agentInfo.getAgentName());
        List<AgentInfo> agentInfoList = agentInfoMapper.selectAgentInfoList(info);
        if (CollectionUtils.isNotEmpty(agentInfoList)) {
            throw new BusinessException("当前服务商名称已存在");
        }
        return agentInfoMapper.updateAgent(agentInfo);
    }


    /**
     * 服务商档位降级
     *
     * @Param [agentInfo]
     * @Return int
     */
    public int updateAgentRainGrade(AgentInfo agentInfo) {
        int i = agentInfoMapper.updateAgent(agentInfo);
        if (i > 0) {
            AgentInfo targetAgent = agentInfoMapper.selectAgentInfoById(agentInfo.getAgentNum());

            //现在的档位信息
            GearsInfo gearsInfo1 = gearsInfoMapper.selectGearsInfoById(String.valueOf(targetAgent.getGrade()));
            //要更新后的档位信息
            GearsInfo gearsInfo = gearsInfoMapper.selectGearsInfoById(agentInfo.getSupportLevel());
            //验证分润政策(档位)是否存在
            if (gearsInfo == null || gearsInfo1 == null) {
                LogUtils.logInfo("当前服务商档位不存在,请查看档位政策是否配置");
                throw new BusinessException("当前服务商档位不存在,请查看档位政策是否配置");
            }
            //修改成功并且验证成功后增加修改档位记录（个人降级）
            GearsRecord gearsRecord = new GearsRecord();
            gearsRecord.setAddMan(ShiroUtils.getSysUser().getLoginName());
            gearsRecord.setBefor(targetAgent.getGrade());
            gearsRecord.setBeforDs(gearsInfo1.getDs());
            gearsRecord.setAfter(agentInfo.getSupportLevel());
            gearsRecord.setAfterDs(gearsInfo.getDs());
            gearsRecord.setAgentName(targetAgent.getAgentName());
            gearsRecord.setAgentNum(targetAgent.getAgentNum());
            gearsRecord.setUpdateDate(DateUtils.getTime());
            gearsRecord.setType("5");
            gearsRecordMapper.insertGearsRecord(gearsRecord);
        }
        return i;
    }

    @Override
    @Transactional
    public int updateAgentGrade(AgentInfo agentInfo) {
        return agentInfoMapper.updateAgentGrade(agentInfo);
    }


    @Override
    @Transactional
    public int updateAgentNorm(AgentInfo agentInfo) {
        return agentInfoMapper.updateAgentNorm(agentInfo);
    }

    @Override
    public Integer selectBelongAgent(AgentInfo agentInfo) {
        return agentInfoMapper.selectBelongAgent(agentInfo);
    }

    @Override
    public List<Map<String, Object>> lookSendAgentInfoList(AgentInfo agentInfo) {
        return agentInfoMapper.lookSendAgentInfoList(agentInfo);
    }

    @Override
    public void sendAgentInfo(Map param) {

        String[] agentNums = param.get("agentNum").toString().split(",");
        //1.上送
        //上送资料
        new Thread(new Runnable() {
            @SneakyThrows
            @Override
            public void run() {
                for (String agentNum : agentNums) {
                    Map<String, Object> agentMap = agentInfoMapper.selectAgentInfoMapById(agentNum);
                    //代理基本信息
                    if (!Utils.IsNull(agentMap.get("IDENTITY_NUM"))) {
                        agentMap.put("IDENTITY_NUM", EncryptUtils.getDecrypt(String.valueOf(agentMap.get("IDENTITY_NUM"))));
                    } else {
                        agentMap.put("IDENTITY_NUM", "");
                    }
                    //账户信息
                    String agentInfo = JSON.toJSONString(agentMap);
                    //代理账户信息
                    Map<String, Object> accountMap = accountsMapper.selectAccountsMapBySeqId(agentNum);
                    accountMap.put("SCREEN_NUM", EncryptUtils.getDecrypt(Utils.IsNull(accountMap.get("SCREEN_NUM")) ? "" : accountMap.get("SCREEN_NUM").toString()));
                    accountMap.put("SCREEN_IDNUM", EncryptUtils.getDecrypt(Utils.IsNull(accountMap.get("SCREEN_IDNUM")) ? "" : accountMap.get("SCREEN_IDNUM").toString()));
                    accountMap.put("RESPHONE", EncryptUtils.getDecrypt(Utils.IsNull(accountMap.get("RESPHONE")) ? "" : accountMap.get("RESPHONE").toString()));
                    JSONObject data = new JSONObject();
                    JSONObject sb0 = new JSONObject();
                    JSONObject sb1 = new JSONObject();
                    JSONObject sb2 = new JSONObject();
                    JSONObject sb3 = new JSONObject();
                    ClientImg clientImg = new ClientImg();
                    clientImg.setClientno(agentNum);
                    List<Map<String, Object>> clientImgs = clientImgMapper.selectclientImgMapList(clientImg);
                    for (Map ct : clientImgs) {

                        if (String.valueOf(ct.get("TYPE")).equals("5") || String.valueOf(ct.get("TYPE")).equals("1") || String.valueOf(ct.get("TYPE")).equals("2")) {
                            sb0.put(ct.get("FILEID").toString().substring(ct.get("FILEID").toString().lastIndexOf("/") + 1), CustomConfig.getImgUrl() + ct.get("FILEID"));
                            sb1.put(ct.get("FILEID").toString().substring(ct.get("FILEID").toString().lastIndexOf("/") + 1), CustomConfig.getImgUrl() + ct.get("FILEID"));
                        } else if (String.valueOf(ct.get("TYPE")).equals("19") || String.valueOf(ct.get("TYPE")).equals("20") || String.valueOf(ct.get("TYPE")).equals("21") || String.valueOf(ct.get("TYPE")).equals("3") || String.valueOf(ct.get("TYPE")).equals("39") || String.valueOf(ct.get("TYPE")).equals("38")) {
                            if (!Utils.IsNull(ct.get("FILEID"))) {
                                sb3.put(ct.get("FILEID").toString().substring(ct.get("FILEID").toString().lastIndexOf("/") + 1), CustomConfig.getImgUrl() + ct.get("FILEID"));
                            }
                        } else if (String.valueOf(ct.get("TYPE")).equals("4") || String.valueOf(ct.get("TYPE")).equals("18")) {
                            if (!Utils.IsNull(ct.get("FILEID"))) {
                                sb2.put(ct.get("FILEID").toString().substring(ct.get("FILEID").toString().lastIndexOf("/") + 1), CustomConfig.getImgUrl() + ct.get("FILEID"));
                            }
                        }
                    }
                    data.put("00", sb0);
                    data.put("01", sb1);
                    data.put("02", sb2);
                    data.put("03", sb3);
                    JSONObject request = new JSONObject();
                    request.put("agentInfo", agentInfo);
                    request.put("accounts", JSONObject.toJSONString(accountMap));
                    request.put("fileData", data);
                    request.put("agent_type", "3");  //1钱宝 3展业端管理
                    String send = HttpUtils.send(AutoLoadData.sendAgentInfo, request, "utf-8");
                    System.out.println(agentMap.get("AGENT_NUM") + send);
                    JSONObject result = JSONObject.parseObject(send);
                    if ("A10".equals(result.get("code"))) {
                        agentMap.put("AGENT_TYPE", 3);
                        //成功才记录
                        agentInfoMapper.markSendAgentInfoResult(agentMap);
                    }

                }
            }
        }).start();
    }

    /**
     * 服务商送审
     *
     * @Param [agentInfo]
     * @Return int
     */
    @Transactional
    @Override
    public int audit(AgentInfo agentInfo) {
        AgentInfo agentInfo1 = agentInfoMapper.selectAgentInfoById(agentInfo.getAgentNum());
        //先查询一下防止数据状态延迟
        if (agentInfo1.getAgentStatus().equals("2")) {
            throw new BusinessException("当前服务商已送审,请勿重复送审");
        }
        //修改服务商状态
        //送审之后 修改服务商状态为审核中
        AgentInfo agent = new AgentInfo();
        agent.setAgentStatus("2");
        agent.setAgentNum(agentInfo.getAgentNum());
        return agentInfoMapper.updateAgentInfo(agent);
    }

    /**
     * 查询登录代理团队信息
     *
     * @param agentNum 服务商申请ID
     * @return 服务商申请
     */
    @Override
    public List<AgentInfo> selectAgentListBy(AgentInfo agentNum) {

        return agentInfoMapper.selectAgentListBy(agentNum);
    }

    /**
     * 获取顶级代理商
     *
     * @param agentInfo
     * @return
     */
    public List<AgentInfo> selectTopAgentInfo(AgentInfo agentInfo) {
        return agentInfoMapper.selectTopAgentInfo(agentInfo);
    }

    /**
     * @Param [merNo 要迁移的商户编号, agentNum 要迁移的代理商编号]
     * @Return int
     */
    @Transactional
    @Override
    public AjaxResult agentMigrateUpdate(String agentNum, String agentName, String newBelongAgent, String newBelongAgentName) {
        try {
            LogUtils.logInfo("开始迁移代理商:" + agentNum);
            AgentInfo agentInfo = agentInfoMapper.selectAgentInfoById(agentNum);
            //原上级代理商编号
            String belongAgent = agentInfo.getBelongAgent().toString();
            //原上级代理编号和要迁移代理不可相同
            if (newBelongAgent.equals(belongAgent)) {
                LogUtils.logInfo("已经所属目标代理商,不可重复迁移");
                return AjaxResult.error("已经所属目标代理商,不可重复迁移");
            }
            if (agentNum.equals(newBelongAgent)){
                LogUtils.logInfo("不可迁移代理商本身");
                return AjaxResult.error("不可迁移代理商本身");
            }
            AgentInfo agentInfo1 = agentInfoMapper.selectAgentInfoById(newBelongAgent);
            // 0 正常代理
            if (!"0".equals(agentInfo.getAgentStatus()) && !"0".equals(agentInfo1.getAgentStatus())) {
                LogUtils.logInfo("代理商状态非正常,请先确认代理商状态");
                return AjaxResult.error("代理商状态非正常代理,请先确认代理商状态");
            }

            AgentTotal agentTotal1 = agentTotalMapper.selectAgentTotalByAgentNum(agentNum);
            Long id = agentTotal1.getId();
            AgentTotal agentTotal = new AgentTotal();
            agentTotal.setId(id);
            agentTotal.setAgentNum(agentNum);
            agentTotal.setBelongAgent(newBelongAgent);
            agentTotalMapper.updateAgentTotal(agentTotal);

            AgentInfo agentInfo2 = new AgentInfo();
            agentInfo2.setAgentNum(agentNum);
            agentInfo2.setBelongAgent(Long.parseLong(newBelongAgent));
            agentInfoMapper.updateAgent(agentInfo2);

            //代理迁移记录
            MerRecord merRecord = new MerRecord();
            merRecord.setMerNo(agentNum);
            merRecord.setAgentNum(belongAgent);
            merRecord.setNewAgentNum(newBelongAgent);
            merRecord.setNote("代理迁移");
            merRecord.setCreateDate(DateUtils.getDateTime());
            merRecord.setType("3");
            merRecord.setOperation(ShiroUtils.getLoginName());
            merRecordMapper.insertMerRecord(merRecord);
        } catch (Exception e) {
            e.printStackTrace();
            LogUtils.logInfo("迁移异常" + e);
            return AjaxResult.error("迁移异常");
        }
        LogUtils.logInfo("迁移成功" + agentNum);
        return AjaxResult.success("迁移成功");
    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult saveUpdateBank(Map<String, String> params) {
        params.put("merno",params.get("agentNum"));
        Accounts accounts = new Accounts();
        accounts.setSeqId(params.get("agentNum"));
        accounts.setScreenName(params.get("screenName"));
        try {
            accounts.setScreenIdnum(EncryptUtils.getEncrypt(params.get("screenIdnum")));
            accounts.setResphone(EncryptUtils.getEncrypt(params.get("resphone")));
            accounts.setScreenNum(EncryptUtils.getEncrypt(params.get("screenNum")));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        accounts.setShowScreennum(Utils.dealCard(params.get("screenNum")));
        accounts.setShowScreenidnum(params.get("screenIdnum").substring(0, 10) + "****" + params.get("screenIdnum").substring(14));
        accounts.setShowResphone(Utils.dealPhone(params.get("resphone")));
        accounts.setBankHeadname(params.get("headBank"));
        accounts.setBankName(params.get("branchBank"));
        accounts.setBankNum(params.get("subbranchId"));
        Map<String, Object> areaP = new HashMap();
        areaP.put("area_code", params.get("province"));
        areaP.put("area_type", "0");
        Map<String, Object> pMap = areaMapper.findQBAreaName(areaP);
        areaP.put("area_code", params.get("city"));
        areaP.put("area_type", "1");
        Map<String, Object> cMap = areaMapper.findQBAreaName(areaP);
        accounts.setAreaName(pMap.get("AREA_NAME") + "," + cMap.get("AREA_NAME"));
        accounts.setBankAddress(params.get("province") + "," + params.get("city"));
        accounts.setDaMarker(2);
        Accounts ac = new Accounts();
        ac.setSeqId(accounts.getSeqId());
        List<Accounts> accounts1 = accountsMapper.selectAccountsList(ac);
        if (CollectionUtils.isEmpty(accounts1)) {
            accountsMapper.insertAccounts(accounts);
        } else {
            accountsMapper.updateAccountsBySeqId(accounts);
        }

        CardBag c = new CardBag();
        c.setMerno(accounts.getSeqId());
        c.setScreenNumDense(accounts.getScreenNum());
        List<CardBag> cardBags = cardBagMapper.selectCardBagList(c);
        CardBag cardBag = new CardBag();
        //结算卡数据同步卡包表一份
        cardBag.setMerno(accounts.getSeqId());
        cardBag.setLocaldate(DateUtils.getDate());
        cardBag.setAdddate(DateUtils.getOnlyTime());
        cardBag.setScreenName(params.get("screenName"));
        cardBag.setScreenNum(accounts.getShowScreennum());
        cardBag.setScreenNumDense(accounts.getScreenNum());
        cardBag.setiCard(1);
        cardBag.setIdnumber(accounts.getShowScreenidnum());
        cardBag.setIdnumberDense(accounts.getScreenIdnum());
        cardBag.setIsdefault(0);
        cardBag.setBankName(accounts.getBankName());
        cardBag.setBankHeadname(accounts.getBankHeadname());
        cardBag.setResphone(accounts.getShowResphone());
        cardBag.setResphoneDense(accounts.getResphone());
        cardBag.setBankNum(accounts.getBankNum());
        cardBag.setBottomPic("grey");
        cardBag.setPicno("000");
        cardBag.setBankAddress(accounts.getBankAddress());
        cardBag.setAreaName(accounts.getAreaName());
        cardBag.setCardType(1);
        if (CollectionUtils.isEmpty(cardBags)) {
            cardBagMapper.insertCardBag(cardBag);
        } else {
            cardBagMapper.updateCardBag(cardBag);
        }
        return AjaxResult.success();
    }


    @Override
    public AjaxResult saveSetPolicy(Map<String, String> params,String[] actIdss) {
        String agentNum = params.get("agentNum");
        AgentInfo agentInfo = agentInfoMapper.selectAgentInfoById(agentNum);
        if (!agentInfo.getBelongAgent().toString().equals("100000000")) {
            for (String actId : actIdss) {
                AgentActActive aaa = new AgentActActive();
                aaa.setAgentNum(agentInfo.getBelongAgent().toString());
                aaa.setActId(actId);
                ActActive actActive = actActiveMapper.selectActActiveById(actId);
                AgentActActive agentActActive = agentActActiveMapper.selectagentActActiveOne(aaa);
                if (agentActActive == null) {
                    return AjaxResult.error("上级未设置政策【" + actActive.getActName() + "】,请先设置上级政策");
                }
            }

        }

        if (actIdss == null || actIdss.length == 0) {
            agentActActiveMapper.deleteagentActActiveByIdBean(agentNum);
            return AjaxResult.success("政策全部取消成功");
        }
        String actIds = String.join(",", actIdss);
        agentActActiveMapper.deleteagentActActiveByIdNot(agentNum,actIds);
        String[] split = actIds.split(",");
        for (String actId : split) {
            AgentActActive a1 = new AgentActActive();
            a1.setAgentNum(agentNum);
            a1.setActId(actId);
            List<AgentActActive> actives = agentActActiveMapper.selectagentActActiveList(a1);
            if (CollectionUtils.isEmpty(actives)) {
                AgentActActive a = new AgentActActive();
                a.setAgentNum(agentNum);
                a.setActId(actId);
                agentActActiveMapper.insertagentActActive(a);
            }

        }

        return AjaxResult.success();
    }
}
